package com.heima.search.service.impl;


import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void saveSearchRecord(String keyword, Integer userId, String equipmentId) {

        ApUserSearch apUserSearch = new ApUserSearch();

        if (userId != null) {

            apUserSearch.setUserId(userId);
        } else {
            apUserSearch.setEquipmentId(equipmentId);
        }
        apUserSearch.setKeyword(keyword);

        apUserSearch.setCreatedTime(new Date());

        Query query = new Query();

        if (userId != null) {

            query.addCriteria(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(equipmentId).and("keyword").is(keyword));
        }
        boolean exists = mongoTemplate.exists(query, ApUserSearch.class);

        if (!exists) {

            mongoTemplate.save(apUserSearch);
        }
    }

    @Override
    public ResponseResult load(ApArticleSearchDto dto) {

        User user = AppThreadLocalUtil.get();

        Query query = new Query();

        if(user!=null){

            query.addCriteria(Criteria.where("userId").is(user.getUserId())).with(PageRequest.of(0,5, Sort.Direction.DESC,"createdTime"));
        }else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId())).with(PageRequest.of(0,5, Sort.Direction.DESC,"createdTime"));
        }

        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {

        List<ApUserSearch> hisList = dto.getHisList();
        List<String> ids = new ArrayList<>();
        for (ApUserSearch userSearch : hisList) {
            ids.add(userSearch.getId());
        }

        Query query = new Query();

        query.addCriteria(Criteria.where("id").is(ids));

        mongoTemplate.remove(query,ApUserSearch.class);

        return ResponseResult.okResult();
    }
}
